/*
 *  Copyright (C) 2011  Clint Priest
 *
 *  This file is part of pklib.
 *
 *  pklib is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  pklib is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with pklib.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

var ValueSet = Class.create(Array, {
	initialize: function(data) {
		if(data instanceof ValueSet && data.Formatter)
			this.Formatter = data.Formatter;
			
		(data || []).forEach(function(x) {
			this.push(x);
		}, this);
	},
	get Min() {
		return this.reduce( function(val, low) {
			return Math.min(low, val);
		}, Number.MAX_VALUE);
	},
	get Max() {
		return this.reduce( function(val, high) {
			return Math.max(high, val);
		}, -Number.MAX_VALUE);
	},
	get Sum() {
		return this.reduce( function(val, sum) {
			return parseFloat(sum) + val;
		}, 0);
	},
	get Average() {
		if(this.length > 0)
			return this.Sum / this.length;
		return Number.NaN;
	},
	get StdDev() {
		if(this.length >= 2) {
			var Average = this.Average;
			return Math.sqrt(this.reduce( function( sum, val) {
				val = val - Average;
				return sum + ( val * val );
			}, 0) / (this.length - 1));
		}
		return Number.NaN;
	},
	sortNumerically: function() {
		this.sort( function(a, b) {
			return a - b;
		} );
		return this;
	},
	push: function($super, val) {
		if(!this.Formatter)
			this.Formatter = new ValueFormat(val);
		$super(this.Formatter.NumericValue(val));
	},
	concat: function(data) {
		if(Object.isArray(data) || data instanceof ValueSet) {
			var out = new ValueSet(this);
			data.forEach( function(x) {
				out.push(x);
			} );
			return out;
		}
		throw 'ValueSet.concat() requires another ValueSet or array';
	}
} );